<?php

namespace App\Http\Controllers\Web\Seller;

use App\ConstDir\ErrorConst;
use App\Http\Controllers\Web\BaseController;
use App\Repository\Models\Products;
use App\Repository\Repositories\Interfaces\ProductSkusRepository;
use App\Repository\Repositories\Interfaces\ProductsRepository;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Exception;
use App\Repository\Repositories\Interfaces\ProductAttributesRepository;

/**
 * 商品管理控制器
 *
 * @package App\Http\Controllers\Web\Seller
 */
class ProductController extends BaseController
{
   
    protected $product_repo;
    protected $product_sku_repo;
    protected $product_attr_repo;
    
    protected $shop_id;
    protected $user_id;
    public function __construct(ProductsRepository $product_repo,ProductSkusRepository $product_sku_repo,ProductAttributesRepository $product_attr_repo)
    {
        parent::__construct();
        $this->product_repo = $product_repo;
        $this->product_sku_repo = $product_sku_repo;
        $this->product_attr_repo = $product_attr_repo;
        //用户只能操作自身所属数据
  
        $this->shop_id =isset($this->user) &&  isset($this->user->shop_id) ? $this->user->shop_id : 0;
        $this->user_id =isset($this->user) &&  isset($this->user->id) ? $this->user->id : 0;
        
        $this->product_repo->scopeQuery(function ($query) {
            return $query->where('shop_id', $this->shop_id);//->where('status', 1);
        });
    }

    public function index()
    {
        $orders = $this->product_repo->paginate($this->perPage);
        return $this->success(ErrorConst::SUCCESS_CODE_MSG, $orders, true);
    }

    public function show($id)
    {
        $product = $this->product_repo->with('skus')->find($id);
        return $this->success(ErrorConst::SUCCESS_CODE_MSG, $product['data']);
    }

    public function store(Request $request)
    {
        $cate_type = $request->get("cate_type",1);
   
        if($cate_type == 1){
            $this->validate($request,[
                'name'=> 'required|string',
                'brand_id'=>'required|exists:product_brands,id',
                'sort'=>'integer',
            ]);
        }else{
            $this->validate($request,[
                'name'=> 'required|string',
                'sort'=>'integer',
            ]);
        }
       
        
        $data = $request->all();
        $data['status'] = 0;
        $data['shop_id'] = $this->shop_id;
        $data['user_id'] = $this->user_id;
  
        if($cate_type == 1){
            $ret = $this->product_repo->createNew($data);
        }else{
            $data['delivery_time'] = "";
            $data['brand_id'] = 0;
            $data['guarantee_period'] = 0;
            $data['model'] = "";
            $data['skus'] = "";
            $data['product_type'] = $cate_type;
            $ret = $this->product_repo->createNewZZ($data);
        }
  
        return $this->noDataReturn($ret ? true : false);
    }

    public function update(Request $request, $id)
    {
        $this->validate($request,[
            'name'=> 'string',
            'sort'=>'integer',
        ]);
        $data = $request->all();
        $data['shop_id'] = $this->shop_id;
        $data['user_id'] = $this->user_id;
        $data['updated_at']=Carbon::now();
        
        $skus = isset($data['skus']) && $data['skus'] ? $data['skus'] : "";
        if($skus){
            unset($data['skus']);
        }
     
        $pattrs = isset($data['pattrs']) && $data['pattrs'] ? $data['pattrs'] : "";
        if($pattrs){
            unset($data['pattrs']);
        }
        $price = isset($data['price']) && $data['price'] ? $data['price'] : 0;
        DB::beginTransaction();
        try {
            $ret = $this->product_repo->update($data, $id);
            
            if($skus){
                $skus= json_decode($skus,true);
                foreach($skus as &$sku){
                    
                    if(!isset($sku['price']) || !$sku['price']){
                        $sku['price'] = 0;
                    }
                    
                    if($sku['id']){
                        $this->product_sku_repo->update($sku, $sku['id']);
                    }else{
                        $sku['product_id'] =$id;
                        $sku['sku_code'] = 'v'.date("Ymd").$id.rand(10000,100000);
                        $this->product_sku_repo->create($sku);
                    }
                    
                }
            }
            
            if(isset($ret['data']['product_type']) && $ret['data']['product_type'] == 2 && $pattrs ){
                $ret = $this->product_attr_repo->updateWhere(['attributes'=>$pattrs,'price'=>$price],['product_id'=>$id]);
            }
            DB::commit();
        } catch (Exception $e) {
            DB::rollback(); //事务回滚;
            return $this->error(ErrorConst::FAILED_CODE_MSG);
        }
        
        return $this->success(ErrorConst::SUCCESS_CODE, ErrorConst::SUCCESS_CODE_MSG);
    }

    public function delete($id)
    {
        $ret = $this->product_repo->delete($id);
        return $this->noDataReturn($ret ? true : false);
    }
    
    public function batchDelete(Request $request){
        $this->validate($request,[
            'ids'=> 'required|array',
        ]);
        $data = $request->all(['ids']);
      
        $ret = $this->product_repo->batchDelete($data['ids']);
        return $this->noDataReturn($ret ? true : false);
    }
    
    public function batchSale(Request $request){
        $this->validate($request,[
            'ids'=> 'required|array',
            'is_sale'=>'required|integer',
        ]);
        $data = $request->all(['ids','is_sale']);
        
        $ret = $this->product_repo->batchSale($data);
        return $this->noDataReturn($ret ? true : false);
    }
    
    public function cupboardCount(Request $request){
        $this->validate($request,[
            'value' => 'integer',
        ]);
        $data = $request->all(['shop_id','value','product_type']);
        if(!isset($data['value'])){
            $data['value'] = 1;
        }
        
        if(!isset($data['product_type'])){
            $data['product_type'] = 1;
        }
        
        $ret = $this->product_repo->cupboardCount($this->shop_id,$data['value'],$data['product_type']);
        if(isset($ret['data'])){
            return $this->success(ErrorConst::SUCCESS_CODE,count($ret['data']));
        }else{
            return $this->success(ErrorConst::SUCCESS_CODE,0);
        }
        
    }

    public function count(){
        $orders['sale_down'] = Products::query()->where('shop_id', $this->shop_id)->where('is_for_sale',0)->where('product_type',1)->count();
        $orders['sale_on']= Products::query()->where('shop_id', $this->shop_id)->where('is_for_sale',1)->where('product_type',1)->count();

        return $this->success(ErrorConst::SUCCESS_CODE,$orders);

    }
}
